package com.zhouchao.transfer.factory;


import com.alibaba.druid.sql.visitor.functions.If;
import com.zhouchao.transfer.Constants;
import com.zhouchao.transfer.annotation.Autowired;
import com.zhouchao.transfer.annotation.Component;
import com.zhouchao.transfer.annotation.Transactional;
import com.zhouchao.transfer.service.impl.TransferServiceImpl;
import com.zhouchao.transfer.utils.ScanUtil;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Stream;

/**
 * @author 应癫
 * <p>
 * 工厂类，生产对象（使用反射技术）
 */
public class BeanFactory {

    /**
     * 任务一：读取解析xml，通过反射技术实例化对象并且存储待用（map集合）
     * 任务二：对外提供获取实例对象的接口（根据id获取）
     */
    // 存储创建完成的对象
    private final static ConcurrentHashMap<String, Object> singletonObjects = new ConcurrentHashMap<>();

    // 缓存未完成属性注入的的对象
    private final static ConcurrentHashMap<String, Object> earlySingletonObjects = new ConcurrentHashMap();

    static {
//        getBeanFromXML();
        getBeanFromAnnotation();
    }

    private static void getBeanFromAnnotation() {
        try {
            // 获取指定目录下的文件
            Set<String> files = ScanUtil.scanPackage(Constants.CLASSPATH_ALL_URL_PREFIX);
            for (String f : files) {
                Class<?> clazz = BeanFactory.class.getClassLoader().loadClass(f);
                if (clazz.isAnnotationPresent(Component.class)){
                    Object object = clazz.newInstance();
                    earlySingletonObjects.put(getBeanName(clazz), object);
                }
            }

            for (String key : earlySingletonObjects.keySet()) {
                if (singletonObjects.containsKey(key)) {
                    continue;
                }
                Object object = earlySingletonObjects.get(key);
                injectComponents(object);
            }

            System.out.println("bean初始化完毕。。。");

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("类扫描异常");
        }

    }

    private static Object injectComponents(Object o) {
        Class<?> clazz = o.getClass();
        String id = getBeanName(clazz);
        try {
            // 获取需要注入的属性
            Stream.of(clazz.getDeclaredFields())
                    .filter(field -> {
                        int mod = field.getModifiers();
                        return !Modifier.isStatic(mod) &&
                                field.isAnnotationPresent(Autowired.class);
                    })
                    // 注入属性
                    .forEach(field -> {
                        Class<?> c = field.getType();
                        // 判断是否是接口，如果是接口就看他又没有注解，如果是类，就先获取接口
                        Object reference = null;
                        reference = singletonObjects.get(c.getName());
                        if (reference == null) {
                            reference = earlySingletonObjects.get(c.getName());
                            injectComponents(reference);
                        }
                        field.setAccessible(true);
                        try {
                            field.set(o, reference);
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
        earlySingletonObjects.remove(id);
        singletonObjects.put(id, o);
        return o;
    }


    static void getBeanFromXML() {
        // 任务一：读取解析xml，通过反射技术实例化对象并且存储待用（map集合）
        // 加载xml
        InputStream resourceAsStream = BeanFactory.class.getClassLoader().getResourceAsStream("beans.xml");
        // 解析xml
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();
            List<Element> beanList = rootElement.selectNodes("//bean");
            for (int i = 0; i < beanList.size(); i++) {
                Element element = beanList.get(i);
                // 处理每个bean元素，获取到该元素的id 和 class 属性
                String id = element.attributeValue("id");        // accountDao
                String clazz = element.attributeValue("class");  // com.lagou.edu.dao.impl.JdbcAccountDaoImpl
                // 通过反射技术实例化对象
                Class<?> aClass = Class.forName(clazz);
                Object o = aClass.newInstance();  // 实例化之后的对象

                // 存储到map中待用
                singletonObjects.put(id, o);

            }

            // 实例化完成之后维护对象的依赖关系，检查哪些对象需要传值进入，根据它的配置，我们传入相应的值
            // 有property子元素的bean就有传值需求
            List<Element> propertyList = rootElement.selectNodes("//property");
            // 解析property，获取父元素
            for (int i = 0; i < propertyList.size(); i++) {
                Element element = propertyList.get(i);   //<property name="AccountDao" ref="accountDao"></property>
                String name = element.attributeValue("name");
                String ref = element.attributeValue("ref");

                // 找到当前需要被处理依赖关系的bean
                Element parent = element.getParent();

                // 调用父元素对象的反射功能
                String parentId = parent.attributeValue("id");
                Object parentObject = singletonObjects.get(parentId);
                // 遍历父对象中的所有方法，找到"set" + name
                Method[] methods = parentObject.getClass().getMethods();
                for (int j = 0; j < methods.length; j++) {
                    Method method = methods[j];
                    if (method.getName().equalsIgnoreCase("set" + name)) {  // 该方法就是 setAccountDao(AccountDao accountDao)
                        method.invoke(parentObject, singletonObjects.get(ref));
                    }
                }

                // 把处理之后的parentObject重新放到map中
                singletonObjects.put(parentId, parentObject);

            }


        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }


    // 任务二：对外提供获取实例对象的接口（根据id获取）
    public static Object getBean(String id) {
        return singletonObjects.get(id);
    }

    public static Object getSingleton(String beanName) {
        Object singletonObject = null;
        synchronized (singletonObjects) {
            singletonObject = singletonObjects.get(beanName);
            if (singletonObject == null) {
                singletonObject = earlySingletonObjects.get(beanName);
            }
        }
        return singletonObject;
    }

    public static Object getBean(Class<?> clazz) {
        String beanName = getBeanName(clazz);
        return getBean(beanName);
    }

    private static String getBeanName(Class<?> clazz) {
        Component comp = clazz.getAnnotation(Component.class);
        String beanName = null;
        if (comp == null || StringUtils.isEmpty(comp.value())) {
            Class<?>[] interfaces = clazz.getInterfaces();
            if (interfaces != null && interfaces.length > 0) {
                beanName = interfaces[0].getName();
            } else {
                beanName = clazz.getName();
            }
        } else {
            beanName = comp.value();
        }
        return beanName;
    }

}
